package org.depsea.oss.client.minio;

import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.http.Method;
import lombok.Setter;
import org.depsea.oss.client.PresignedUrlGenerator;
import org.depsea.oss.exception.OssGetFileException;

import java.util.Map;
import java.util.concurrent.TimeUnit;

public class MinioPresignedUrlGenerator implements PresignedUrlGenerator {

    private final MinioClient minioClient;
    private final String defaultBucketName;

    @Setter
    private int expirationSecond;

    public MinioPresignedUrlGenerator(MinioClient minioClient, String defaultBucketName) {
        this.minioClient = minioClient;
        this.defaultBucketName = defaultBucketName;
        this.expirationSecond = (int) TimeUnit.SECONDS.toMillis(15);
    }

    @Override
    public String generate(String fullPath) {
        return this.generateByBucket(this.defaultBucketName, fullPath);
    }

    @Override
    public String generateByBucket(String bucketName, String fullPath) {
        try {
            return minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket(bucketName)
                            .object(fullPath)
                            .expiry(expirationSecond, TimeUnit.SECONDS)
                            .build());
        } catch (Exception e) {
            throw new OssGetFileException("Failed to generate presigned url", e);
        }
    }

    @Override
    public String generateWithArguments(String fullPath, Map<String, String> arguments) {
        return this.generateByBucket(this.defaultBucketName, fullPath);
    }

    @Override
    public String generateByBucketWithArguments(String bucketName, String fullPath, Map<String, String> arguments) {
        return this.generateByBucket(bucketName, fullPath);
    }
}
